<template>
	<view>

		<!-- 拍照结果 -->
		<view class="full-screen-width flex justify-around padding-xl">
			<image :src="uploadRes" class="radius shadow-blur" mode="scaleToFill"></image>
		</view>

		<!-- 识别结果 -->
		<view class="cu-bar bg-white margin-top">
			<view class="action">
				<text class="cuIcon-titles text-green"></text>
				{{predictionRes.length == 0 ? '正在识别……' : '检测到以下可能'}}
			</view>
		</view>
		<view>
			<view class="bg-white padding padding-left-xl padding-right-xl" v-for="(item, index) in predictionRes" :key="index">
				<view class="flex justify-between ">
					<view class="bg-white text-white">{{index+1}}</view>
					<view class="text-bold text-lg">{{item.name}}</view>
					<view class="text-green">{{parseInt(item.score* 100)}}%</view>
				</view>
				<view class="text-df margin-top-sm margin-left-sm margin-bottom-xs">{{item.baike_info.description}}</view>
				<u-line></u-line>
			</view>
		</view>

		<!-- 上传数据 -->
		<view v-if="id.length == 0" class="flex justify-around margin-top-xl">
			<button class="cu-btn round lg bg-gradual-green shadow-blur" @click="saveRes">保存结果</button>
		</view>

		<view>
			<u-modal v-model="showModal" content="您的积分不住，请前往获取" @confirm="confirm" :show-cancel-button="true"></u-modal>
		</view>

	</view>
</template>

<script>
	import {
		mapGetters,
		mapActions
	} from 'vuex';
	export default {
		data() {
			return {
				uploadRes: '',
				predictionRes: [],
				id: '',
				showModal: false,
				type: 1
			};
		},
		async onLoad(option) {
			const item = JSON.parse(decodeURIComponent(option.item))
			this.uploadRes = item.uploadRes
			this.type = item.type
			if (item._id != 0) {
				this.fetchCloudData(item._id)
			} else {
				this.prediction(item)
			}
			console.log("这是type", this.type)
		},
		methods: {
			...mapActions(['getUser']),
			async fetchCloudData(_id) {
				uni.showLoading({
					mask: true,
					title: '正在加载'
				})
				this.id = _id
				const { result: { code, msg, data } } = await wx.cloud.callFunction({ name: 'pet', data: { $url: 'getIdentifyById', identifyId: _id } })
				if (code === 200) {
					this.predictionRes = data.identify
					this.uploadRes = data.imageUrl
				}
				uni.hideLoading()
			},
			async getAccessToken(type) {
				let AK = "yhrUSJ9Cg87atgumSNrNmNEh";
				let SK = "5Im88qdmtLS07eea2pNwnwrTPYuO2jFU";
				if (type == 2) {
					AK = "5fxvfAceGxeqzWQu2A2k1xuw";
					SK = "179ALfLkV6yjCQIEex9JzLf5YCXxyyeY"
				}
				return new Promise((resolve, reject) => {
					uni.request({
						url: 'https://aip.baidubce.com/oauth/2.0/token',
						method: 'POST',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						data: {
							grant_type: 'client_credentials',
							client_id: AK,
							client_secret: SK
						},
						success: (res) => {
							if (res.statusCode === 200) {
								resolve(res.data.access_token);
							} else {
								reject(new Error(`Failed to fetch access token: ${JSON.stringify(res.data)}`));
							}
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},
			async prediction(params) {
				if (!this.isLogin) {
					this.$toast({ title: "请先登录" });
					return;
				}
				if (this.userInfo.integral <= 0) {
					this.showModal = true;
					return;
				}

				uni.showLoading({ mask: true, title: '正在识别' });

				let imageUrl = params.uploadRes;
				// 如果图像是云存储中的，则获取临时链接
				if (imageUrl.split(':')[0] === 'cloud') {
					const res = await wx.cloud.getTempFileURL({
						fileList: [imageUrl],
					});
					imageUrl = res.fileList[0].tempFileURL;
				}

				try {
					const accessToken = await this.getAccessToken(this.type);
					async function consumeIntegral(activity) {
						const { result: { code, msg } } = await wx.cloud.callFunction({
							name: 'user',
							data: { $url: 'consumeIntegral', consume: { remark: activity, num: 2 } }
						});
						if (code !== 200) {
							throw new Error(`消费积分失败: ${msg}`);
						}
						console.log("消费积分成功");
					}

					if (this.type == 2) {
						// 获取图片数据并转换为Base64
						const res = await new Promise((resolve, reject) => {
							uni.request({
								url: imageUrl,
								method: 'GET',
								responseType: 'arraybuffer',
								success: resolve,
								fail: reject
							});
						});
						let base64 = uni.arrayBufferToBase64(res.data)

						// 发送请求到百度AI
						const aiResponse = await new Promise((resolve, reject) => {
							uni.request({
								url: `https://aip.baidubce.com/rpc/2.0/ai_custom_bml/v1/classification/dcSkinDisease?access_token=${accessToken}`,
								method: 'POST',
								header: { 'Content-Type': 'application/json' },
								data: { image: base64, top_num: 1 },
								success: resolve,
								fail: reject
							});
						});
						this.predictionRes = aiResponse.data.results;
						await consumeIntegral('动物诊疗');
					} else {
						const aiResponse = await new Promise((resolve, reject) => {
							uni.request({
								url: `https://aip.baidubce.com/rest/2.0/image-classify/v1/animal?access_token=${accessToken}`,
								method: 'POST',
								header: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' },
								data: { url: imageUrl, top_num: 1, baike_num: 1 },
								success: resolve,
								fail: reject
							});
						});
						this.predictionRes = aiResponse.data.result;

						await consumeIntegral('动物识别');
					}
				} catch (error) {
					console.error(error);
					this.$toast({ title: error.message || "请求过程中出现错误" });
				} finally {
					uni.hideLoading();
				}
			},

			async saveRes() {
				if (this.predictionRes.length == 0) {
					this.$toast({
						title: '未检测到结果,保存失败'
					})
					return
				}
				const addPetIdentify = {
					imageUrl: this.uploadRes,
					time: new Date(),
					identify: JSON.parse(JSON.stringify(this.predictionRes))
				}
				uni.showLoading({
					mask: true,
					title: '正在保存'
				})
				const { result: { code, msg, data } } = await wx.cloud.callFunction({ name: 'pet', data: { $url: 'saveIdentify', addPetIdentify: addPetIdentify } })

				if (code == 200) {
					uni.showToast({
						mask: true,
						icon: 'none',
						title: '保存成功'
					})
				} else {
					uni.showToast({
						mask: true,
						icon: 'none',
						title: '保存失败'
					})
				}
			},
			confirm() {
				uni.navigateTo({
					url: "/pages_subpackage/integral_history/integral_history"
				})
			}

		},
		computed: {
			...mapGetters(['userInfo', 'isLogin'])
		}
	}
</script>

<style lang="scss">
	image {
		width: 50vw;
		height: 50vw;
	}
</style>